package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private CommentApi commentApi;


    /**
     * 用户管理基本资料列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findUsers(Integer page, Integer pagesize) {
        //分页查询
        IPage<UserInfo> iPage = userInfoApi.findAllUsers(page, pagesize);
        List<UserInfo> records = iPage.getRecords();
        for (UserInfo userInfo : records) {
            String key = Constants.FREEZE_USER + userInfo.getId();
            if (redisTemplate.hasKey(key)) {
                userInfo.setUserStatus("2");
            }
        }
        return new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 通过id查询 用户基本资料
     *
     * @param userId
     * @return
     */
    public UserInfo findByUserId(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        String key = Constants.FREEZE_USER + userId;
        if (redisTemplate.hasKey(key)) {
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    /**
     * 根据id视频记录翻页
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResult findByVideo(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByVideo(page, pagesize, uid);
    }

    /**
     * 动态分页查询
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    public PageResult findMessages(Integer page, Integer pagesize, Long uid, String state) {
        //查询movment对象
        List<Movement> items = null;
        if (state == null) {
            items = movementApi.findMessages(page, pagesize, uid, null);
        } else {
            items = movementApi.findMessages(page, pagesize, uid, Integer.valueOf(state));
        }
        //将每一个movment转化为vo对象
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        //获取所有id
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, movement);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,vos.size(),vos);
    }

    /**
     * 用户冻结
     *
     * @param map
     * @return
     */
    public Map usersFreeze(Map map) {
        //获取冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        String freezingTime = String.valueOf(map.get("freezingTime"));
        //获取将要冻结的用户id
        String userId = map.get("userId").toString();
        //初始冻结值；
        int days = 0;
        //判断要冻结时间
        if ("1".equals(freezingTime)) {
            days = 3;
        } else if ("2".equals(freezingTime)) {
            days = 7;
        }
        //将数据转成json
        String value = JSON.toJSONString(map);
        //将数据存入redis缓存中
        if (days > 0) {
            redisTemplate.opsForValue().set(Constants.FREEZE_USER + userId, value, days, TimeUnit.MINUTES);
        } else {
            redisTemplate.opsForValue().set(Constants.FREEZE_USER + userId, value);
        }
        Map resultMap = new HashMap();
        resultMap.put("message", "冻结成功！");
        //返回消息
        return resultMap;
    }

    /**
     * 用户解冻
     *
     * @param map
     * @return
     */
    public Map usersUnFreeze(Map map) {
        //获取冻结用户id
        String userId = String.valueOf(map.get("userId"));
        //通过id在redis中进行删除
        redisTemplate.delete(Constants.FREEZE_USER + userId);
        Map resultMap = new HashMap();
        resultMap.put("message", "解冻成功！");
        //返回消息
        return resultMap;
    }


    /**
     * 动态详情查询
     *
     * @param messageId
     * @return
     */
    public MovementsVo findMovment(String messageId) {
        //通过id获取单条动态详情
        Movement movement = movementApi.findByid(messageId);
        //根据动态获取当前用户的id
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        //构造MovementsVo对象，并返回
        return MovementsVo.init(userInfo, movement);
    }

    /**
     * 根据动态查询单条动态的评论
     *
     * @param page
     * @param pagesize
     * @param messageID
     * @return
     */
    public PageResult findComments(Integer page, Integer pagesize, String messageID) {
        //调用api分页查询
        List<Comment> comments = commentApi.findAllComments(page, pagesize, messageID);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //提取被评论列表的id
        List<Long> publishUserIds = CollUtil.getFieldValues(comments, "publishUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(publishUserIds, null);
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getPublishUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, vos.size(), vos);
    }
}
